# modify /dev/pts/21.... 
# then sudo python3  z.py 
# in browser: http://222.191.202.174:8888/cmdSendToVi?cmd=\\x1b:set\\x20nu\\n表示ESC:set nonu回车
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import cgi
import subprocess
from urllib import request, parse
import shutil
import sys

data = {'userGives': 'this is a test'}
host = ('0.0.0.0', 8888)
ptsNo="23"

class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
       self.send_response(200)
       tosearch = self.path[1:] + '_'
       print(tosearch)

       if( tosearch.rfind('cmdSendToVi')>-1 ):
         enc = "UTF-8"
         self.send_header("Content-type", "text/html;charset=%s" % enc)
         self.end_headers()
         zstr = (parse.parse_qs( tosearch ))['cmdSendToVi?cmd']
         zstr2 = (zstr[0])[:-1]
         if( int(zstr2) <= 10 ):
           zcmd = "python zsend.py /dev/pts/" + ptsNo + "  \\\\x0" + hex(int(zstr2))[2:]
         else:
           zcmd = "python zsend.py /dev/pts/" + ptsNo + "  \\\\" + hex(int(zstr2))[1:]
         print(zcmd);
         z = subprocess.Popen( zcmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True).stdout.read()
         self.wfile.write( ("<pre>").encode())
         self.wfile.write( zcmd.encode() )
         #self.wfile.write( ("<br>--------<br>").encode() )
         #self.wfile.write( z.decode('utf-8').encode() ) 
         self.wfile.write( ("</pre>").encode())
       else: # requesting an html
         enc = "UTF-8"
         self.send_header("Content-type", "text/html;charset=%s" % enc)
         self.end_headers()
         buf=open( tosearch[:-1],'r',encoding="utf-8").read()
         self.wfile.write( buf.encode() )

server = HTTPServer(host, Resquest)
server.serve_forever()
